package com.zbc.demo.exception;

import com.zbc.demo.enums.GlobalExceptionEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.http.HttpStatus;

import java.util.Objects;

/**
 * 自定义异常类
 *
 * @author 万恶的沫白
 * @date 2021/8/13
 */

@Data
@EqualsAndHashCode(callSuper = true)
public class BaseException extends RuntimeException {
    private int code;
    private String message;


    private BaseException() {
    }

    public BaseException(GlobalExceptionEnum error) {
        this.code = error.getCode();
        this.message = error.getMessage();
    }

    /**
     * 根据code获取http 状态码,code的前三位和http 状态码一致
     * 不符合规则，默认返回 400
     *
     * @return http 状态码
     */
    public HttpStatus getHttpStatus() {
        //判断code是否为3位数
        if (!this.verifyCode()) {
            //不符合返回400
            return HttpStatus.BAD_REQUEST;
        }
        String codeStr = String.valueOf(this.code).substring(0, 3);
        int statusCode = Integer.parseInt(codeStr);

        HttpStatus httpStatus = HttpStatus.resolve(statusCode);

        if (Objects.isNull(httpStatus)) {
            //不符合返回400
            return HttpStatus.BAD_REQUEST;
        }
        return httpStatus;
    }

    /**
     * 校验code code 最少是3位数
     *
     * @return 符合校验true, 否则false
     */
    public boolean verifyCode() {
        return this.code >= 100;
    }
}
